package org.koyad.portal.db;

import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.koyad.portal.constants.FrameworkConstants;
import org.koyad.portal.context.PistonContext;
import org.koyad.portal.exceptions.ErrorCodes;
import org.koyad.portal.exceptions.FrameworkException;
import org.koyad.portal.utils.LogUtils;

public class PistonDBManager {
	
	private static final LogUtils LOGGER = LogUtils
			.getLogger(PistonDBManager.class);
	
	public static Connection getConnection() throws FrameworkException {
		Connection conn = null;
		try {
			String dbURL = "jdbc:derby:" + System.getProperty("user.home") + "\\piston-derby-db;create=true";
			LOGGER.info("Getting connection for DB : " + dbURL);
			conn = DriverManager.getConnection(dbURL);
			
//			Context ctx = new InitialContext();
//			DataSource ds = (DataSource)ctx.lookup("java:comp/env/jdbc/pistonDB");
//			conn = ds.getConnection();
		} catch (Exception e) {
			LOGGER.logException(e);
			throw new FrameworkException(FrameworkConstants.FWKDB001);
		}
		
		return conn;
	}
	
	public static DBObjectsWrapper executeQuery(String query) {
		Connection conn = null;
		Statement stmt = null;
		ResultSet rs = null;
		try {
			//This should not be done for java SE 6
			Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance();
			
			conn = PistonDBManager.getConnection();
			conn.setAutoCommit(true);
			
			stmt = conn.createStatement();
			
			rs = stmt.executeQuery(query);
			
			return new DBObjectsWrapper(rs, stmt, conn);
			
		} catch (Exception e) {
			LOGGER.logException(e);
			
			if(null != stmt) {
				try {
					stmt.close();
				} catch (SQLException ex) {
					LOGGER.logException(ex);
				}
			}
			if(null != conn) {
				try {
					conn.close();
				} catch (SQLException ex) {
					LOGGER.logException(ex);
				}
			}
			
			PistonContext.getContext().getViewRoot().addError(ErrorCodes.FWKPB001);
		} 
		
		return null;
		
	}

	public static void close(DBObjectsWrapper dbObjectsWrapper) {
		if(null != dbObjectsWrapper.getResultSet()) {
			try {
				dbObjectsWrapper.getResultSet().close();
			} catch (SQLException ex) {
				LOGGER.logException(ex);
			}
		}
		
		if(null != dbObjectsWrapper.getStatement()) {
			try {
				dbObjectsWrapper.getStatement().close();
			} catch (SQLException ex) {
				LOGGER.logException(ex);
			}
		}
		if(null != dbObjectsWrapper.getConnection()) {
			try {
				dbObjectsWrapper.getConnection().close();
			} catch (SQLException ex) {
				LOGGER.logException(ex);
			}
		}
		
	}
}
